import matplotlib.pyplot as plt
import numpy as np
from keras.layers import Dense
from keras.models import Sequential

X = np.linspace(-2, 6, 200)
np.random.shuffle(X)
Y = 0.5 * X + 2 + 0.15 * np.random.randn(200, )


X_train, Y_train = X[:160], Y[:160]
X_test, Y_test = X[160:], Y[160:]


model = Sequential()
model.add(Dense(1, input_shape=(1,)))

# 随机梯度下降
model.compile(optimizer="sgd", loss="mse")

epoch = 1000
split1 = 0.01
for step in range(epoch):
    cost = model.train_on_batch(X_train, Y_train)

loss_and_metrics = model.evaluate(X_test, Y_test, batch_size=1)
W, b = model.layers[0].get_weights()
print('Weights=', W, '\nbiases=', b)

Y_pre = model.predict(X_test)
plt.scatter(X_test, Y_test)
plt.plot(X_test, Y_pre)
plt.show()

